<template>
  <a-skeleton :loading="loading" active :title="false" :paragraph="{ rows: 2, width: '100%' }">
    <a-card title="菜单分配" size="small" :bordered="false" hoverable>
      <template #extra>
        <a-button
          type="primary"
          :disabled="!showButton"
          @click="saveMenu"
          v-auth="['admin', 'roles:edit']"
        >
          <template #icon>
            <CheckOutlined />
          </template>
          保存
        </a-button>
      </template>
      <a-tree
        checkable
        checkStrictly
        :load-data="onLoadData"
        :tree-data="treeData"
        v-model:expandedKeys="expandedKeys"
        v-model:checkedKeys="checkedKeys"
      >
      </a-tree>
    </a-card>
  </a-skeleton>
</template>
<script lang="ts">
  import { defineComponent, ref, toRaw, onMounted } from 'vue';
  import { notification } from 'ant-design-vue';
  import { CheckOutlined } from '@ant-design/icons-vue';
  import { showButton, currentId, checkedKeys, reload } from './index';
  import { getMenusLazyApi } from '/@/api/menu';
  import { editRoleMenuApi } from '/@/api/role';

  export default defineComponent({
    components: {
      CheckOutlined,
    },
    setup() {
      const loading = ref<boolean>(true);
      const treeData = ref<any>([]);
      const expandedKeys = ref<any[]>([]);

      const hasLeaf = (list: Array<any>) => {
        list.forEach((item) => {
          item.key = item.id;
          if (item.leaf) {
            item.isLeaf = item.leaf;
          }
        });
        return list;
      };

      const getMenus = async (pid) => {
        try {
          let res = await getMenusLazyApi({ pid });
          treeData.value = hasLeaf(res || []);
        } catch (error) {}
      };

      onMounted(async () => {
        setTimeout(async () => {
          loading.value = false;
        }, 300);
        currentId.value = null;
        expandedKeys.value = [];
        checkedKeys.value = [];
        await getMenus(0);
      });

      const onLoadData = (treeNode: any) => {
        return new Promise((resolve: (value?: unknown) => void) => {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
          setTimeout(async () => {
            let res = await getMenusLazyApi({ pid: treeNode.dataRef.id });
            treeNode.dataRef.children = hasLeaf(res || []);
            resolve();
          }, 200);
        });
      };

      const saveMenu = async () => {
        // 得到已选中的 key 值
        if (checkedKeys.value.checked) {
          const role: any = { id: currentId.value, menus: [] };
          toRaw(checkedKeys.value.checked).forEach(function (id) {
            const menu = { id: id };
            role.menus.push(menu);
          });
          await editRoleMenuApi(role);
          reload.value = !reload.value;
          notification['success']({
            message: '保存成功!',
            duration: 3,
          });
        }
      };

      return { loading, showButton, treeData, expandedKeys, checkedKeys, onLoadData, saveMenu };
    },
  });
</script>
